package com.lapelittle.framework.utils;

import java.util.ArrayList;
import java.util.List;

public class QueryBuilder {
    public StringBuilder sql;
    public List<Object> params;
    public boolean hasWhere;
    
    public QueryBuilder(String baseSql) {
        this.sql = new StringBuilder(baseSql);
        this.params = new ArrayList<>();
        this.hasWhere = baseSql.toLowerCase().contains("where");
    }
    
    public QueryBuilder and(String condition, Object value) {
        if (value != null) {
            if (!hasWhere) {
                sql.append(" WHERE ");
                hasWhere = true;
            } else {
                sql.append(" AND ");
            }
            sql.append(condition);
            params.add(value);
        }
        return this;
    }
    
    public QueryBuilder andLike(String field, String value) {
        if (value != null && !value.isEmpty()) {
            if (!hasWhere) {
                sql.append(" WHERE ");
                hasWhere = true;
            } else {
                sql.append(" AND ");
            }
            sql.append(field).append(" LIKE ?");
            params.add("%" + value + "%");
        }
        return this;
    }
    
    public QueryBuilder andIn(String field, List<?> values) {
        if (values != null && !values.isEmpty()) {
            if (!hasWhere) {
                sql.append(" WHERE ");
                hasWhere = true;
            } else {
                sql.append(" AND ");
            }
            sql.append(field).append(" IN (");
            for (int i = 0; i < values.size(); i++) {
                if (i > 0) {
                    sql.append(",");
                }
                sql.append("?");
                params.add(values.get(i));
            }
            sql.append(")");
        }
        return this;
    }
    
    public QueryBuilder andBetween(String field, Object start, Object end) {
        if (start != null && end != null) {
            if (!hasWhere) {
                sql.append(" WHERE ");
                hasWhere = true;
            } else {
                sql.append(" AND ");
            }
            sql.append(field).append(" BETWEEN ? AND ?");
            params.add(start);
            params.add(end);
        }
        return this;
    }
    
    public String getSql() {
        return sql.toString();
    }
    
    public Object[] getParams() {
        return params.toArray();
    }
}